package com.lht.femalecat.netty.resolve.other;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

import java.net.InetSocketAddress;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author:骆宏图
 * @CreateDate: 14:22 2018/7/28.
 * @Description:
 * @Modified By:
 */
public class TimeServer {
    public static void main(String[] args) throws Exception {
        new TimeServer().bind("127.0.0.1", 8400);
    }


    public void bind(String addr, int port) {
        //配置服务端的nio线程组
        EventLoopGroup boosGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(boosGroup, workerGroup);
            b.channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 1024)
                    .childHandler(new ChildChannelHandler());
            //绑定端口，同步等待成功
            ChannelFuture f = b.bind(new InetSocketAddress(addr, port)).sync();
            System.out.println("启动服务器:" + f.channel().localAddress());
            //等等服务器端监听端口关闭
            f.channel().closeFuture().sync();
        } catch (Exception e) {
            // TODO: handle exception
        } finally {
            boosGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            System.out.println(ch.remoteAddress());
            ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
            ch.pipeline().addLast(new StringDecoder());//增加解码器
            ch.pipeline().addLast(new TimeServerHandler());

        }

    }


    private class TimeServerHandler extends ChannelInboundHandlerAdapter {

        private int counter;

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            String body = (String) msg;
            System.out.println("服务端收到：" + body + "，次数:" + ++counter);
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = dateFormat.format(new Date());
            byte[] res =( "来自与服务端的回应,时间:" + time+System.getProperty("line.separator")).getBytes();
            ByteBuf resp = Unpooled.buffer(res.length);
            resp.writeBytes(res);
            ctx.writeAndFlush(resp);

        }


        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            ctx.close();
        }


    }
}
